<script setup lang="ts">
import {
  NForm,
  NInput,
  NSelect,
  NButton,
  NFormItem,
  NDatePicker,
  NInputNumber,
  NTreeSelect,
  useMessage,
  type UploadFileInfo,
  type SelectOption
} from 'naive-ui'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import { onMounted, ref, reactive } from 'vue'
import type { BatchDetailModel } from '@/api/batchV2'
import type { DicTreeModel } from '@/api/dic'
import type { HttpResponse } from '@/utils/http'
import VAttachments from '@/views/OA/Common/Attachments.vue'

const route = useRoute()
const message = useMessage()

const clueSelectOptions = ref<SelectOption[]>([])
const clueSelectLoading = ref(false)
const queryClueSelectOptions = async () => {
  clueSelectLoading.value = true
  try {
    const [error, res] = await sendRequest<HttpResponse<DicTreeModel[]>>({
      module: 'batchV2',
      api: 'clueList'
    })

    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    clueSelectOptions.value = res.data
  } catch (error) {
    console.error(error)
  } finally {
    clueSelectLoading.value = false
  }
}

const clueMethodOptions = reactive<DicTreeModel[]>([])
const clueMethodLoading = ref(false)
const queryClueMethodOptions = async () => {
  clueMethodLoading.value = true
  try {
    const [error, res] = await sendRequest<HttpResponse<DicTreeModel[]>>({
      module: 'dic',
      api: 'getTree',
      override: {
        params: {
          dicCode: 'A30'
        }
      }
    })

    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    clueMethodOptions.length = 0
    clueMethodOptions.push(...(res.data[0] ? res.data[0].children || [] : []))
  } catch (error) {
    console.error(error)
  } finally {
    clueMethodLoading.value = false
  }
}

const collectorName = ref<string | null>(null)
const batchInfo = ref({} as BatchDetailModel)
const queryBatchInfo = async () => {
  const [error, res] = await sendRequest<HttpResponse<BatchDetailModel>>({
    module: 'batchV2',
    api: 'detail',
    override: {
      params: {
        id: batchId
      }
    }
  })
  if (error) return message.error(error.message)

  sendRequest({
    module: 'clue',
    api: 'infoManage',
    uri: {
      id: res.data.clueId
    }
  })
    .then(([_, cr]) => {
      if (cr) {
        sendRequest({
          module: 'collector',
          api: 'info',
          uri: {
            id: cr.data.collectorId
          }
        })
          .then(([_, er]) => {
            if (er) collectorName.value = er.data.userName
          })
          .catch(() => (collectorName.value = null))
      }
    })
    .catch(() => (collectorName.value = null))

  if (res.data.endTime) {
    res.data.endTime = res.data.endTime.slice(0, 10)
  }
  if (res.data.startTime) {
    res.data.startTime = res.data.startTime.slice(0, 10)
  }
  if (res.data.solicitNum) {
    res.data.solicitNum = Number(res.data.solicitNum)
  }
  batchInfo.value = res.data
  if (res.data.fileIds) queryFileList(res.data.fileIds)
}

let batchId = ''
const queryWorkFlow = async () => {
  const [error, res] = await sendRequest({
    module: 'djRecord',
    api: 'workFlow',
    override: {
      params: {
        djRecordId: route.query.id
      }
    }
  })

  if (error) throw error
  if (res.code !== 0) throw new Error(res.msg)
  batchId = res.data.batchId
}

const fileList = ref<UploadFileInfo[]>([])
const queryFileList = async (filesIds: string) => {
  try {
    const [error, res] = await sendRequest<
      HttpResponse<
        {
          name: string
          path: string
          id: string
          type: string
        }[]
      >
    >({
      module: 'upload',
      api: 'list',
      override: {
        params: {
          ids: filesIds
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    fileList.value = res.data.map((e) => ({
      id: e.id,
      path: e.path,
      name: e.name,
      url: e.path,
      status: 'success'
    })) as unknown as UploadFileInfo[]
  } catch (error) {
    console.error(error)
  }
}

onMounted(async () => {
  await queryWorkFlow()
  queryBatchInfo()
  queryClueSelectOptions()
  queryClueMethodOptions()
})
</script>

<template>
  <div class="bi-title">批次信息</div>
  <DetailFormProvider>
    <NForm
      disabled
      label-placement="left"
      label-width="100rem"
      :show-feedback="false"
      :show-require-mark="false"
      class="bi-card form"
    >
      <NFormItem label="关联线索：">
        <NSelect
          :value="batchInfo.clueId"
          :options="clueSelectOptions"
          :loading="clueSelectLoading"
          placeholder="/"
        />
      </NFormItem>
      <NFormItem label="批次名称：">
        <NInput
          :value="batchInfo.name"
          placeholder="/"
        />
      </NFormItem>
      <NFormItem label="征集方式：">
        <NTreeSelect
          :value="batchInfo.solicitMethodCode"
          :options="clueMethodOptions"
          :loading="clueMethodLoading"
          placeholder="/"
          key-field="code"
          label-field="name"
        />
      </NFormItem>
      <NFormItem label="接收时间：">
        <NDatePicker
          :formatted-value="batchInfo.receiveTime"
          type="datetime"
          placeholder="/"
        />
      </NFormItem>
      <NFormItem label="接收人：">
        <NInput
          :value="batchInfo.receiver"
          placeholder="/"
        />
      </NFormItem>
      <NFormItem label="征集数量：">
        <NInputNumber
          :value="batchInfo.solicitNum"
          placeholder="/"
          :show-button="false"
          :min="0"
          :max="Number.MAX_SAFE_INTEGER"
        />
      </NFormItem>
      <NFormItem label="证书发放：">
        <NInput
          :value="batchInfo.certificateType"
          placeholder="/"
        >
          <template #suffix>
            <NButton
              v-if="batchInfo.certificateType"
              color="#6CB187"
              ghost
              size="small"
              @click="
                $router.push({
                  name: 'DonationCertificateDetail',
                  params: { id: batchInfo.certificateId }
                })
              "
            >
              查看详情
            </NButton>
          </template>
        </NInput>
      </NFormItem>
      <template v-if="batchInfo.solicitMethodCode == 'A3007'">
        <NFormItem label="开始时间：">
          <NDatePicker
            :formatted-value="batchInfo.startTime"
            type="date"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="结束时间：">
          <NDatePicker
            :formatted-value="batchInfo.endTime"
            type="date"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="代存期限：">
          <NInput
            :value="batchInfo.depositPeriod"
            placeholder="/"
          />
        </NFormItem>
      </template>

      <NFormItem label="藏家：">
        <NInput
          v-model:value="collectorName"
          placeholder="/"
          disabled
        />
      </NFormItem>
      <NFormItem label="移交人：">
        <NInput
          v-model:value="batchInfo.transferor"
          placeholder="/"
          disabled
          style="flex-shrink: 2"
        />
        <NInput
          v-model:value="batchInfo.transferorPhone"
          placeholder="/"
          disabled
        />
      </NFormItem>

      <NFormItem label="创建时间：">
        <NDatePicker
          :formatted-value="batchInfo.createTime"
          type="datetime"
          placeholder="/"
        />
      </NFormItem>
      <NFormItem label="修改时间：">
        <NDatePicker
          :formatted-value="batchInfo.updateTime"
          type="datetime"
          placeholder="/"
        />
      </NFormItem>
      <NFormItem label="鉴定状态：">
        <NInput
          :value="batchInfo.identifyStatus"
          placeholder="/"
        />
      </NFormItem>
      <NFormItem
        label="备注："
        class="n-form-item--textarea"
      >
        <NInput
          :value="batchInfo.remark"
          type="textarea"
          placeholder="/"
          rows="5"
        />
      </NFormItem>
      <NFormItem label="附件：">
        <VAttachments
          v-if="batchInfo.fileIds"
          :attach-list="fileList"
        />
      </NFormItem>
    </NForm>
  </DetailFormProvider>
</template>

<style lang="scss" scoped>
.bi-title {
  font-size: 26rem;
  margin-bottom: 30rem;
  color: #048c5e;
  line-height: 1;
}

.bi-card {
  padding: 20rem;
  background-color: #e1e1e1;

  &.form {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16rem 32rem;

    .n-form-item--textarea {
      grid-column: 1 / -1;
    }

    .n-date-picker,
    .n-input-number {
      flex: 1;
    }
  }
}
</style>
